package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.githang.statusbar.StatusBarCompat;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.db.CustomerDB;
import com.ramos.kuaixiao.entity.Customer;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

public class BindShopActivity extends BaseAllTabActivity implements View.OnClickListener {
    private static String TAG = "BindShopActivity";
    private LinearLayout title_reback;
    private TextView title_text;
    Customer mCustomer;

    private EditText shop_id;
    private EditText shop_phone;
    private String mIdStr = "";
    private String mPhoneStr = "";
    private Button btn_bind;
    CommonLoading loading;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;

    String customerId = "";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_shop);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title), false);
        title_reback = (LinearLayout) findViewById(R.id.title_reback);
        title_reback.setOnClickListener(this);
        shop_id = (EditText) findViewById(R.id.shop_id);
        shop_phone = (EditText) findViewById(R.id.shop_phone);
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("绑定账号");
        btn_bind = (Button) findViewById(R.id.btn_bind);
        btn_bind.setOnClickListener(this);
        mCustomer = (Customer) getIntent().getExtras().get("customer");
        if(mCustomer != null) {
            customerId = mCustomer.getId();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_reback:
                finish();
                break;

            case R.id.btn_bind:
                submitBind();
                break;

            default:
                break;
        }
    }

    private void submitBind() {
        mIdStr = shop_id.getText().toString();
        mPhoneStr = shop_phone.getText().toString();
        if (StringUtil.isEmpty(mIdStr)) {
            ToastUtils.show("请输入账号");
            return;
        }
        if (StringUtil.isEmpty(mPhoneStr)) {
            ToastUtils.show("请填入电话");
            return;
        } else{
            if(!Utils.isMobileNO(mPhoneStr)){
                ToastUtils.show("请填入正确的手机号码(非固定电话)");
                return;
            }
        }
        try {
            String url = NetUtils.BIND_SHOP;
            loading = new CommonLoading(this);
            loading.setLoadText("账号绑定中...");
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(10000);
            // 创建请求参数的封装的对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("customerId", customerId);
            jsonObject.put("uid", mIdStr);
            jsonObject.put("telephone", mPhoneStr);
            jsonObject.put("saleId", SharedPreference.getPreferString("id"));
            jsonObject.put("dealerId", SharedPreference.getPreferString("dealer"));
            Log.d(TAG, "submitBind " + url);
            Log.d(TAG, "submitBind " + jsonObject.toString());
            ByteArrayEntity stringEntity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
            stringEntity.setContentType("application/json");
            // 执行post方法
            client.put(this, url, stringEntity, "application/json", new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
                    loading.dismiss();
                    Log.d(TAG, "submitBind " + responseBody.toString());
                    try {
                        if (responseBody.getInt("status") == 200) {
                            sendMessagea(UPLOAD_SUCCESS, responseBody.getString("msg"));
                        } else {
                            sendMessagea(UPLOAD_FAIL, responseBody.getString("msg"));
                        }
                    } catch (JSONException e) {
                        sendMessagea(UPLOAD_FAIL, "绑定失败");
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    loading.dismiss();
                    sendMessagea(UPLOAD_FAIL, "绑定失败");
                    throwable.printStackTrace();// 把错误信息打印出轨迹来
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            sendMessagea(UPLOAD_FAIL, "绑定失败");
            e.printStackTrace();
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    new CustomerDB().bindCustomer(customerId, mPhoneStr,mIdStr );
                    ToastUtils.show("绑定成功,可使用此账号登陆");
                    finish();
                    break;
                case UPLOAD_FAIL:
                    ToastUtils.show(msg.obj.toString());
                    break;
                default:
                    break;
            }
        }
    };

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }
}


